package org.tinaelle.client.gui.grid;

import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.Store;
import com.gwtext.client.widgets.PagingToolbar;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.ToolTip;
import com.gwtext.client.widgets.form.Field;
import com.gwtext.client.widgets.form.NumberField;
import com.gwtext.client.widgets.form.event.FieldListenerAdapter;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.RowSelectionModel;
import com.gwtext.client.widgets.grid.event.RowSelectionListenerAdapter;
import com.gwtext.client.widgets.layout.FitLayout;

public class DataGrid2<T> extends Panel {

	public DataGrid2(final Store store, final DynaTableDataProvider<T> dataProvider, final DataDetail<T> dataDetail) {
		setLayout( new FitLayout() );

		final GridPanel grid = new GridPanel( store, dataProvider.getColumnModel() );
		grid.setAutoWidth( true );
		grid.setLoadMask( true );
		// grid.setWidth(500);
		// grid.setHeight(400);
		// grid.setTitle("Grid that uses GWTProxy to load data from server");

		final RowSelectionModel sm = new RowSelectionModel( true );
		sm.addListener( new RowSelectionListenerAdapter() {
			@Override
			public void onRowSelect(final RowSelectionModel sm, final int rowIndex, final Record record) {
				dataDetail.setCurrentRecord( record );
			}
		} );
		grid.setSelectionModel( sm );

		final PagingToolbar pagingToolbar = new PagingToolbar( store );
		pagingToolbar.setPageSize( 15 );
		pagingToolbar.setDisplayInfo( true );
		pagingToolbar.setDisplayMsg( "Displaying records {0} - {1} of {2}" );
		pagingToolbar.setEmptyMsg( "No records to display" );

		final NumberField pageSizeField = new NumberField();
		pageSizeField.setWidth( 40 );
		pageSizeField.setSelectOnFocus( true );
		pageSizeField.addListener( new FieldListenerAdapter() {
			@Override
			public void onSpecialKey(final Field field, final EventObject e) {
				if ( e.getKey() == EventObject.ENTER ) {
					final int pageSize = Integer.parseInt( field.getValueAsString() );
					pagingToolbar.setPageSize( pageSize );
				}
			}
		} );

		final ToolTip toolTip = new ToolTip( "Enter page size" );
		toolTip.applyTo( pageSizeField );

		pagingToolbar.addField( pageSizeField );
		grid.setBottomToolbar( pagingToolbar );
		store.load( 0, pagingToolbar.getPageSize() );

		add( grid );
	}

}
